<?php
/**
 * Created by PhpStorm.
 * User: macmini
 * Date: 2018/3/1
 * Time: 上午11:17
 */

namespace app\api\controller;

use app\common\controller\Api;
use think\Cache;
use think\captcha\Captcha;
use think\Cookie;

class Index extends Api 
{
    public function get_captcha($id)
    {
        $config =    [
            // 验证码字体大小
            'fontSize'    =>    30,
            // 验证码位数
            'length'      =>    4,
            // 关闭验证码杂点
            'useNoise'    =>    false,
            'useCurve' => false,
        ];
        session_start();
        $s_id = session_id();
        $model = db('code');
        $info = $model->where('id', $id)->find();
        if ($info) {
            $model->where('id', $id)->update(['session_id'=>$s_id]);
        } else {
            $model->insert(['id' => $id, 'session_id' => $s_id]);
        }
        $captcha = new Captcha($config);
        return $captcha->entry($id);
    }

    // 检测输入的验证码是否正确，$code为用户输入的验证码字符串，$id多个验证码标识
    function check_verify($code, $id = '')
    {

        $captcha = new Captcha();
        return $captcha->check($code, $id);
    }

    public function cates()
    {
        $info = db('Cates')->select();
        $res = db('Cates')->where('pid', 0)->select();
        foreach ($res as &$v) {
            foreach ($info as $vo) {
                if ($vo['pid'] == $v['id']) {
                    $v['next'][] = $vo;
                }
            }
        }
        return $this->responseSend(0, $res, 200);
    }

    public function goods($cid = 0)
    {
        $where = [
            'status' => 1
        ];
        if ($cid) {
            $cate_info = db('cates')->where('id', $cid)->find();
            if ($cate_info['pid'] == 0) {
                $cate_infos = db('cates')->where('pid', $cid)->select();
                $ids = [$cid];
                foreach ($cate_infos as $v) {
                    $ids[] = $v['id'];
                }
                $where['cid'] = ['in',$ids];
            } else {
                $where['cid'] = $cid;
            }

            $res = model('Goods')->where($where)->paginate(20,false,[
                'query' => request()->get()
            ])->each(function ($item,$key){
                $item['head_img'] = unserialize($item['head_img']);
            });
            foreach ($res as &$v) {
                $sku_first = db('sku')->where('goods_id', $v['id'])->order('price asc')->find();
                $sku_last = db('sku')->where('goods_id', $v['id'])->order('price desc')->find();
                if ($sku_first['price'] == $sku_last['price']) {
                    $v['price'] = $sku_last['price'];
                } else {
                    $v['price'] = $sku_first['price'].'~'.$sku_last['price'];
                }
            }
        } else {
            $res = db('cates')->where('pid', 0)->select();
            foreach ($res as &$v) {
                $next = db('cates')->where('pid', $v['id'])->select();
                $ids = [$v['id']];
                foreach ($next as $vo) {
                    $ids[] = $vo['id'];
                }
                $goods_info = db('goods')->where(['cid' => ['in',$ids]])->select();
                foreach ($goods_info as &$i) {
                    $sku_first = db('sku')->where('goods_id', $i['id'])->order('price asc')->find();
                    $sku_last = db('sku')->where('goods_id', $i['id'])->order('price desc')->find();
                    if ($sku_first['price'] == $sku_last['price']) {
                        $i['price'] = $sku_last['price'];
                    } else {
                        $i['price'] = $sku_first['price'].'~'.$sku_last['price'];
                    }

                    $i['head_img'] = unserialize($i['head_img']);
                }
                $v['next'] = $next;
                $v['goods'] = $goods_info;
            }
        }
        //var_dump(gettype($res));die;
        return $this->responseSend(0, $res, 200);
    }

    public function format()
    {
        $data = request()->post();
        $user_id = $this->getUserId($data['token']);
        if ($user_id == 300) {
            return $this->responseSend(0, '', 300);
        }
        $res = db('sku')->where('goods_id', $data['goods_id'])->select();
        foreach ($res as &$v) {
            $info = db('SkuItem')->where('sku_id', $v['id'])->select();
            $name = $v['name'];
            foreach ($info as $vo) {
                $r = db('items')->where('id', $vo['item_id'])->find();
                $name .= '+' . $r['name'];
            }
            $v['name'] = $name;
        }
        return $this->responseSend(0, $res, 200);
    }

    public function order()
    {
        $token = request()->post('token');
        $skuInfo = json_decode(request()->post('skuInfo'),true);
        $user_id = $this->getUserId($token);
        if ($user_id == 300) {
            return $this->responseSend(0, '', 300);
        }
        $price = 0;
        $data = [];
        $orderids = [];
        db('sku')->startTrans();
        foreach ($skuInfo as $v) {
            $orderids[] = $v['id'];
            $res = db('sku')->where('id', $v['sku_id'])->find();
            if ($res['number'] < $v['number']) {
                db('sku')->rollback();
                return $this->responseSend($user_id['user_id'],'部分商品库存不足',101);
            }
            db('sku')->where('id', $v['sku_id'])->setDec('number', $v['number']);
            db('goods')->where('id', $res['goods_id'])->setDec('number', $v['number']);
            $sku_money = $res['price'] * $v['number'];
            $price += $sku_money;
            $data[] = [
                'sku_id' => $v['sku_id'],
                'number' => $v['number'],
                'money'  => $sku_money,
            ];
        }
        $userInfo = db('Users')->where('id', $user_id['user_id'])->find();
        if ($userInfo['money'] < $sku_money) {
            db('sku')->rollback();
            return $this->responseSend($user_id['user_id'],'您的余额不够',160);
        }
        db('sku')->commit();
        $order_data = [
            'money' => $price,
            'user_id' => $user_id['user_id'],
            'status' => 1,
            'address_id' => request()->post('address_id'),
            'create_at' => time(),
            'update_at' => time(),
            'orderNo'   => date('YmdHis').uniqid()
        ];
        $order_id = db('orders')->insertGetId($order_data);
        foreach ($data as &$v) {
            $v['order_id'] = $order_id;
        }
        //var_dump($data);die;
        db('OrderDetails')->insertAll($data);
        db('Users')->where('id', $user_id['user_id'])->setDec('money',$price);
        db('ShopCar')->where(['id' => ['in',$orderids]])->delete();
        return $this->responseSend($user_id['user_id'],'',200);

    }

    public function getCates($cid)
    {
        $cate_info = db('cates')->where('id', $cid)->find();
        if ($cate_info['pid'] == 0) {
            $res = db('cates')->where('pid', $cate_info['id'])->select();
        } else {
            $res = db('cates')->where('pid', $cate_info['pid'])->select();
        }
        return $this->responseSend(0, $res, 200);
    }

    public function goodsInfo($goodsId)
    {
        $goodsInfo = db('goods')->where('id', $goodsId)->find();
        $goodsInfo['head_img'] = unserialize($goodsInfo['head_img']);
        $sku_first = db('sku')->where('goods_id', $goodsInfo['id'])->order('price asc')->find();
        $sku_last = db('sku')->where('goods_id', $goodsInfo['id'])->order('price desc')->find();
        if ($sku_first['price'] == $sku_last['price']) {
            $goodsInfo['price'] = $sku_last['price'];
        } else {
            $goodsInfo['price'] = $sku_first['price'].'~'.$sku_last['price'];
        }
        $res = db('sku')->where('goods_id', $goodsId)->select();
        foreach ($res as &$v) {
            $info = db('SkuItem')->where('sku_id', $v['id'])->select();
            $name = $v['name'];
            foreach ($info as $vo) {
                $r = db('items')->where('id', $vo['item_id'])->find();
                $name .= '+' . $r['name'];
            }
            $v['name'] = $name;
        }
        $comments = db('comments')
            ->alias('a')
            ->field('a.content,a.create_at,b.username')
            ->join('users b','a.uid=b.id','left')
            ->where('a.goods_id', $goodsId)
            ->select();
        $goodsInfo['comments'] = $comments;
        $goodsInfo['format'] = $res;
        return $this->responseSend(0, $goodsInfo, 200);
    }
}
